package com.boot.notes.rocketmq.transactionMsg;


import com.boot.common.constant.rocket.ConsumerGroupConstant;
import com.boot.common.constant.rocket.TopicConstant;
import com.boot.modules.admin.service.RedPacketService;
import com.boot.notes.rocketmq.transactionMsg.entity.Order;
import com.boot.notes.rocketmq.transactionMsg.entity.RedPacket;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 消费消息
 * @className: RedPacketListener
 * @auther: mkq
 * @date: 2022/01/22 10:29
 * @desctiption: TODO
 * @version: 1.0
 */
@Component
@RocketMQMessageListener(topic = TopicConstant.TRANSACTION_TOPIC, consumerGroup = ConsumerGroupConstant.CONSUMER_GROUP)
public class RedPacketListener implements RocketMQListener<Order> {

    @Autowired
    private RedPacketService redPacketService;

//    @Override
//    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
//        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
//    }

    @Override
    public void onMessage(Order order) {
        // 一般真实环境这里消费前，得做幂等性判断，防止重复消费
        // 方法一：如果你的业务中有某个字段是唯一的，有标识性，如订单号，那就可以用此字段来判断
        // 方法二：新建一张消费记录表t_mq_consumer_log，字段consumer_key是唯一性，能插入则表明该消息还未消费，往下走，否则停止消费
        // 我个人建议用方法二，根据你的项目业务来定义key，这里我就不做幂等判断了，因为此案例只是模拟，重在分布式事务
        System.out.println("接收到订单系统发来的消息。。。");
//        Order order = JSON.parseObject(msg, Order.class);
        RedPacket redPacket = new RedPacket();
        redPacket.setUserId(order.getUserId());
        redPacket.setOrderId(order.getId());
        redPacket.setTotalFee(order.getTotalFee());
        redPacket.setGmtCreate(new Date());
        redPacket.setGmtModified(new Date());
        redPacketService.sellRedPacket(redPacket);
    }

}